<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
  <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
  <style type="text/css">
    .highlight { display: block; background-color: #ddd; }
  </style>
  <script type="text/javascript">
    function highlight() {
      document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
    }
  </script>
</head>
<body onload="prettyPrint(); highlight();">
  <pre class="prettyprint lang-js"><span id='global-property-'>/**
</span> * @ignore
 * image dialog (support upload and remote)
 * @author yiminghe@gmail.com
 */
KISSY.add(&quot;editor/plugin/image/dialog&quot;, function (S, IO, Editor, Dialog4E, Tabs, MenuButton, bodyTpl) {
    var dtd = Editor.XHTML_DTD,
        UA = S.UA,
        Node = KISSY.NodeList,
        HTTP_TIP = &quot;http://&quot;,
        AUTOMATIC_TIP = &quot;自动&quot;,
        MARGIN_DEFAULT = 10,
        IMAGE_DIALOG_BODY_HTML = bodyTpl,

        IMAGE_DIALOG_FOOT_HTML = &quot;&lt;div style='padding:5px 20px 20px;'&gt;&quot; +
            &quot;&lt;a &quot; +
            &quot;href='javascript:void(\'确定\')' &quot; +
            &quot;class='{prefixCls}img-insert {prefixCls}button ks-inline-block' &quot; +
            &quot;style='margin-right:30px;'&gt;确定&lt;/a&gt; &quot; +
            &quot;&lt;a  &quot; +
            &quot;href='javascript:void(\'取消\')' &quot; +
            &quot;class='{prefixCls}img-cancel {prefixCls}button ks-inline-block'&gt;取消&lt;/a&gt;&lt;/div&gt;&quot;,

        warning = &quot;请点击浏览上传图片&quot;,

        valInput = Editor.Utils.valInput;

    function findAWithImg(img) {
        var ret = img;
        while (ret) {
            var name = ret.nodeName();
            if (name == &quot;a&quot;) {
                return ret;
            }
            if (dtd.$block[name] || dtd.$blockLimit[name]) {
                return null;
            }
            ret = ret.parent();
        }
        return null;
    }

    function ImageDialog(editor, config) {
        var self = this;
        self.editor = editor;
        self.imageCfg = config || {};
        self.cfg = self.imageCfg[&quot;upload&quot;] || null;
        self.suffix = self.cfg &amp;&amp; self.cfg[&quot;suffix&quot;] || &quot;png,jpg,jpeg,gif&quot;;
        // 不要加g：http://yiminghe.javaeye.com/blog/581347
        self.suffix_reg = new RegExp(self.suffix.split(/,/).join(&quot;|&quot;) + &quot;$&quot;, &quot;i&quot;);
        self.suffix_warning = &quot;只允许后缀名为&quot; + self.suffix + &quot;的图片&quot;;
    }

    S.augment(ImageDialog, {
        _prepare: function () {
            var self = this;
            var editor = self.editor,
                prefixCls = editor.get('prefixCls') + 'editor-';
            self.dialog = self.d = new Dialog4E({
                width: 500,
                headerContent: &quot;图片&quot;,
                bodyContent: S.substitute(IMAGE_DIALOG_BODY_HTML, {
                    prefixCls: prefixCls
                }),
                footerContent: S.substitute(IMAGE_DIALOG_FOOT_HTML, {
                    prefixCls: prefixCls
                }),
                mask: true
            }).render();

            var content = self.d.get(&quot;el&quot;),
                cancel = content.one(&quot;.&quot; + prefixCls + &quot;img-cancel&quot;),
                ok = content.one(&quot;.&quot; + prefixCls + &quot;img-insert&quot;),
                verifyInputs = Editor.Utils.verifyInputs,
                commonSettingTable = content.one(&quot;.&quot; + prefixCls + &quot;img-setting&quot;);
            self.uploadForm = content.one(&quot;.&quot; + prefixCls + &quot;img-upload-form&quot;);
            self.imgLocalUrl = content.one(&quot;.&quot; + prefixCls + &quot;img-local-url&quot;);
            self.tab = new Tabs({
                &quot;srcNode&quot;: self.d.get(&quot;body&quot;).one('.' + prefixCls + 'img-tabs'),
                prefixCls: prefixCls + 'img-'
            }).render();
            self.imgLocalUrl.val(warning);
            self.imgUrl = content.one(&quot;.&quot; + prefixCls + &quot;img-url&quot;);
            self.imgHeight = content.one(&quot;.&quot; + prefixCls + &quot;img-height&quot;);
            self.imgWidth = content.one(&quot;.&quot; + prefixCls + &quot;img-width&quot;);
            self.imgRatio = content.one(&quot;.&quot; + prefixCls + &quot;img-ratio&quot;);
            self.imgAlign = MenuButton.Select.decorate(content.one(&quot;.&quot; + prefixCls + &quot;img-align&quot;), {
                prefixCls: prefixCls + 'big-',
                width: 80,
                menuCfg: {
                    prefixCls: prefixCls + '',
                    render: content
                }
            });
            self.imgMargin = content.one(&quot;.&quot; + prefixCls + &quot;img-margin&quot;);
            self.imgLink = content.one(&quot;.&quot; + prefixCls + &quot;img-link&quot;);
            self.imgLinkBlank = content.one(&quot;.&quot; + prefixCls + &quot;img-link-blank&quot;);
            var placeholder = Editor.Utils.placeholder;
            placeholder(self.imgUrl, HTTP_TIP);
            placeholder(self.imgHeight, AUTOMATIC_TIP);
            placeholder(self.imgWidth, AUTOMATIC_TIP);
            placeholder(self.imgLink, &quot;http://&quot;);

            self.imgHeight.on(&quot;keyup&quot;, function () {
                var v = parseInt(valInput(self.imgHeight));
                if (!v || !self.imgRatio[0].checked ||
                    self.imgRatio[0].disabled || !self.imgRatioValue) {
                    return;
                }
                valInput(self.imgWidth, Math.floor(v * self.imgRatioValue));
            });

            self.imgWidth.on(&quot;keyup&quot;, function () {
                var v = parseInt(valInput(self.imgWidth));
                if (!v || !self.imgRatio[0].checked ||
                    self.imgRatio[0].disabled || !self.imgRatioValue) {
                    return;
                }
                valInput(self.imgHeight, Math.floor(v / self.imgRatioValue));
            });

            cancel.on(&quot;click&quot;, function (ev) {
                self.d.hide();
                ev.halt();
            });

            var loadingCancel = new Node(&quot;&lt;a class='&quot; + prefixCls + &quot;button ks-inline-block' &quot; +
                &quot;style='position:absolute;&quot; +
                &quot;z-index:&quot; +
                Editor.baseZIndex(Editor.ZIndexManager.LOADING_CANCEL) + &quot;;&quot; +
                &quot;left:-9999px;&quot; +
                &quot;top:-9999px;&quot; +
                &quot;'&gt;取消上传&lt;/a&gt;&quot;).appendTo(document.body, undefined);

            self.loadingCancel = loadingCancel;

            function getFileSize(file) {
                if (file['files']) {
                    return file['files'][0].size;
                } else if (1 &gt; 2) {
                    //ie 会安全警告
                    try {
                        var fso = new ActiveXObject(&quot;Scripting.FileSystemObject&quot;),
                            file2 = fso['GetFile'](file.value);
                        return file2.size;
                    } catch (e) {
                    }
                }
                return 0;
            }

            ok.on(&quot;click&quot;, function (ev) {
                ev.halt();
                if ((self.imageCfg['remote'] === false ||
                    S.indexOf(self.tab.getSelectedTab(), self.tab.getTabs()) == 1) &amp;&amp;
                    self.cfg) {

                    if (!verifyInputs(commonSettingTable.all(&quot;input&quot;))) {
                        return;
                    }

                    if (self.imgLocalUrl.val() == warning) {
                        alert(&quot;请先选择文件!&quot;);
                        return;
                    }

                    if (!self.suffix_reg.test(self.imgLocalUrl.val())) {
                        alert(self.suffix_warning);
                        // 清除已选文件 ie 不能使用 val(&quot;&quot;)
                        self.uploadForm[0].reset();
                        self.imgLocalUrl.val(warning);
                        return;
                    }

                    var size = (getFileSize(self.fileInput[0]));

                    if (sizeLimit &amp;&amp; sizeLimit &lt; (size / 1000)) {
                        alert(&quot;上传图片最大：&quot; + sizeLimit / 1000 + &quot;M&quot;);
                        return;
                    }

                    self.d.loading();

                   // 取消当前iframe的上传
                    loadingCancel.on(&quot;click&quot;, function (ev) {
                        ev.halt();
                        uploadIO.abort();
                    });

                    var serverParams = Editor.Utils.normParams(self.cfg['serverParams']) || {};

                    // 后端返回设置 domain 的 script，每次都传，防止 domain 中途变化
                    serverParams['document-domain'] = document.domain;

                    var uploadIO = IO({
                        data: serverParams,
                        url: self.cfg['serverUrl'],
                        form: self.uploadForm[0],
                        dataType: 'json',
                        type: 'post',
                        complete: function (data, status) {
                            loadingCancel.css({
                                left: -9999,
                                top: -9999
                            });
                            self.d.unloading();
                            if (status == &quot;abort&quot;) {
                                return;
                            }
                            if (!data) {
                                data = {error: &quot;服务器出错，请重试&quot;};
                            }
                            if (data.error) {
                                alert(data.error);
                                return;
                            }
                            valInput(self.imgUrl, data['imgUrl']);
                            // chrome 中空 iframe 的 img 请求 header 中没有 refer
                            // 在主页面先请求一次，带入 header
                            new Image().src = data['imgUrl'];
                            self._insert();
                        }
                    });

                    var loadingMaskEl = self.d.get(&quot;el&quot;),
                        offset = loadingMaskEl.offset(),
                        width = loadingMaskEl[0].offsetWidth,
                        height = loadingMaskEl[0].offsetHeight;

                    loadingCancel.css({
                        left: (offset.left + width / 2.5),
                        top: (offset.top + height / 1.5)
                    });

                } else {
                    if (!verifyInputs(content.all(&quot;input&quot;)))
                        return;
                    self._insert();
                }
            });

            if (self.cfg) {
                if (self.cfg['extraHTML']) {
                    content.one(&quot;.&quot; + prefixCls + &quot;img-up-extraHTML&quot;)
                        .html(self.cfg['extraHTML']);
                }
                var ke_image_up = content.one(&quot;.&quot; + prefixCls + &quot;image-up&quot;),
                    sizeLimit = self.cfg &amp;&amp; self.cfg['sizeLimit'];

                self.fileInput = new Node(&quot;&lt;input &quot; +
                    &quot;type='file' &quot; +
                    &quot;style='position:absolute;&quot; +
                    &quot;cursor:pointer;&quot; +
                    &quot;left:&quot; +
                    (UA['ie'] ? &quot;360&quot; : (UA[&quot;chrome&quot;] ? &quot;319&quot; : &quot;369&quot;)) +
                    &quot;px;&quot; +
                    &quot;z-index:2;&quot; +
                    &quot;top:0px;&quot; +
                    &quot;height:26px;' &quot; +
                    &quot;size='1' &quot; +
                    &quot;name='&quot; + (self.cfg['fileInput'] || &quot;Filedata&quot;) + &quot;'/&gt;&quot;)
                    .insertAfter(self.imgLocalUrl);
                if (sizeLimit)
                    warning = &quot;单张图片容量不超过 &quot; + (sizeLimit / 1000) + &quot; M&quot;;
                self.imgLocalUrl.val(warning);
                self.fileInput.css(&quot;opacity&quot;, 0);
                self.fileInput.on(&quot;mouseenter&quot;, function () {
                    ke_image_up.addClass(&quot;&quot; + prefixCls + &quot;button-hover&quot;);
                });
                self.fileInput.on(&quot;mouseleave&quot;, function () {
                    ke_image_up.removeClass(&quot;&quot; + prefixCls + &quot;button-hover&quot;);
                });
                self.fileInput.on(&quot;change&quot;, function () {
                    var file = self.fileInput.val();
                    //去除路径
                    self.imgLocalUrl.val(file.replace(/.+[\/\\]/, &quot;&quot;));
                });

                if (self.imageCfg['remote'] === false) {
                    self.tab.removeItemAt(0, 1);
                }
            }
            else {
                self.tab.removeItemAt(1, 1);
            }

            self._prepare = S.noop;
        },

        _insert: function () {
            var self = this,
                url = valInput(self.imgUrl),
                img,
                height = parseInt(valInput(self.imgHeight)),
                width = parseInt(valInput(self.imgWidth)),
                align = self.imgAlign.get(&quot;value&quot;),
                margin = parseInt(self.imgMargin.val()),
                style = '';

            if (height) {
                style += &quot;height:&quot; + height + &quot;px;&quot;;
            }
            if (width) {
                style += &quot;width:&quot; + width + &quot;px;&quot;;
            }
            if (align != 'none') {
                style += &quot;float:&quot; + align + &quot;;&quot;;
            }
            if (!isNaN(margin) &amp;&amp; margin != 0) {
                style += &quot;margin:&quot; + margin + &quot;px;&quot;;
            }

            self.d.hide();

            /*
              2011-01-05
              &lt;a&gt;&lt;img&gt;&lt;/a&gt; 这种结构，a不要设成 position:absolute
              否则img select 不到？!!: editor.getSelection().selectElement(img) 选择不到
             */
            if (self.selectedEl) {
                img = self.selectedEl;
                self.editor.execCommand(&quot;save&quot;);
                self.selectedEl.attr({
                    &quot;src&quot;: url,
                    //注意设置，取的话要从 _ke_saved_src 里取
                    &quot;_ke_saved_src&quot;: url,
                    &quot;style&quot;: style
                });
            } else {
                img = new Node(&quot;&lt;img &quot; +
                    (style ? (&quot;style='&quot; +
                        style +
                        &quot;'&quot;) : &quot;&quot;) +
                    &quot; src='&quot; +
                    url +
                    &quot;' &quot; +
                    &quot;_ke_saved_src='&quot; +
                    url +
                    &quot;' alt='' /&gt;&quot;, null, self.editor.get(&quot;document&quot;)[0]);
                self.editor.insertElement(img);
            }

            // need a breath for firefox
            // else insertElement(img); img[0].parentNode==null
            setTimeout(function () {
                var link = findAWithImg(img),
                    linkVal = S.trim(valInput(self.imgLink)),
                    sel = self.editor.getSelection(),
                    target = self.imgLinkBlank.attr(&quot;checked&quot;) ? &quot;_blank&quot; : &quot;_self&quot;,
                    linkTarget,
                    skip = 0,
                    prev,
                    next,
                    bs;

                if (link) {
                    linkTarget = link.attr('target') || &quot;_self&quot;;
                    if (linkVal != link.attr('href') || linkTarget != target) {
                        img._4e_breakParent(link);
                        if ((prev = img.prev()) &amp;&amp; (prev.nodeName() == 'a') &amp;&amp; !(prev[0].childNodes.length)) {
                            prev.remove();
                        }

                        if ((next = img.next()) &amp;&amp; (next.nodeName() == 'a') &amp;&amp; !(next[0].childNodes.length)) {
                            next.remove();
                        }
                    } else {
                        skip = 1;
                    }
                }

                if (!skip &amp;&amp; linkVal) {
                    // 新增需要 bookmark，标记
                    if (!self.selectedEl) {
                        bs = sel.createBookmarks();
                    }
                    link = new Node(&quot;&lt;a&gt;&lt;/a&gt;&quot;);
                    link.attr(&quot;_ke_saved_href&quot;, linkVal)
                        .attr(&quot;href&quot;, linkVal)
                        .attr(&quot;target&quot;, target);
                    var t = img[0];
                    t.parentNode.replaceChild(link[0], t);
                    link.append(t);
                }

                if (bs) {
                    sel.selectBookmarks(bs);
                }
                else if (self.selectedEl) {
                    self.editor.getSelection().selectElement(self.selectedEl);
                }
                if (!skip) {
                    self.editor.execCommand(&quot;save&quot;);
                }
            }, 100);
        },

        _update: function (selectedEl) {
            var self = this,
                active = 0,
                link,
                resetInput = Editor.Utils.resetInput;
            self.selectedEl = selectedEl;
            if (selectedEl &amp;&amp; self.imageCfg['remote'] !== false) {
                valInput(self.imgUrl, selectedEl.attr(&quot;src&quot;));
                var w = parseInt(selectedEl.style(&quot;width&quot;)),
                    h = parseInt(selectedEl.style(&quot;height&quot;));
                if (h) {
                    valInput(self.imgHeight, h);
                } else {
                    resetInput(self.imgHeight);
                }
                if (w) {
                    valInput(self.imgWidth, w);
                } else {
                    resetInput(self.imgWidth);
                }
                self.imgAlign.set(&quot;value&quot;, selectedEl.style(&quot;float&quot;) || &quot;none&quot;);
                var margin = parseInt(selectedEl.style(&quot;margin&quot;))
                    || 0;
                self.imgMargin.val(margin);
                self.imgRatio[0].disabled = false;
                self.imgRatioValue = w / h;
                link = findAWithImg(selectedEl);
            } else {
                var editor = self.editor;
                var editorSelection = editor.getSelection();
                var inElement = editorSelection &amp;&amp; editorSelection.getCommonAncestor();
                if (inElement) {
                    link = findAWithImg(inElement);
                }
                var defaultMargin = self.imageCfg['defaultMargin'];
                if (defaultMargin == undefined) {
                    defaultMargin = MARGIN_DEFAULT;
                }
                if (self.tab.get('bar').get('children').length == 2) {
                    active = 1;
                }
                self.imgLinkBlank.attr(&quot;checked&quot;, true);
                resetInput(self.imgUrl);
                resetInput(self.imgLink);
                resetInput(self.imgHeight);
                resetInput(self.imgWidth);
                self.imgAlign.set(&quot;value&quot;, &quot;none&quot;);
                self.imgMargin.val(defaultMargin);
                self.imgRatio[0].disabled = true;
                self.imgRatioValue = null;
            }
            if (link) {
                valInput(self.imgLink, link.attr(&quot;_ke_saved_href&quot;) || link.attr(&quot;href&quot;));
                self.imgLinkBlank.attr(&quot;checked&quot;, link.attr(&quot;target&quot;) == &quot;_blank&quot;);
            } else {
                resetInput(self.imgLink);
                self.imgLinkBlank.attr(&quot;checked&quot;, true);
            }
            self.uploadForm[0].reset();
            self.imgLocalUrl.val(warning);
            var tab = self.tab;
            tab.setSelectedTab(tab.getTabAt(active));
        },
        show: function (_selectedEl) {
            var self = this;
            self._prepare();
            self._update(_selectedEl);
            self.d.show();
        },
        destroy: function () {
            var self = this;
            self.d.destroy();
            self.tab.destroy();
            if (self.loadingCancel) {
                self.loadingCancel.remove();
            }
            if (self.imgAlign) {
                self.imgAlign.destroy();
            }
        }
    });

    return ImageDialog;
}, {
    requires: ['io', 'editor', '../dialog', 'tabs', '../menubutton', './dialog/dialog-tpl']
});
</pre>
</body>
</html>
